<template>
  <div>
    <!-- 必要信息 -->
    <el-form
      :inline="true"
      ref="form"
      label-width="80px"
      size="large"
      :model="formData"
      :rules="Rules"
    >
      <el-form-item label="标题" prop="title">
        <el-input v-model="formData.title"></el-input>
      </el-form-item>
      <el-form-item label="作者" prop="author">
        <el-input v-model="formData.author"></el-input>
      </el-form-item>
      <el-form-item label="分类" prop="category">
        <el-select placeholder="请选择分类" v-model="formData.category">
          <el-option
            v-for="item in categories"
            :key="item.id"
            :label="item.category_name"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <br />
      <el-form-item label="概要" prop="abstract">
        <el-input
          class="inputtext"
          type="textarea"
          :rows="5"
          v-model="formData.abstract"
        ></el-input>
      </el-form-item>
      <br />

      <el-form-item label="图片" prop="file">
        <el-upload
          action="http://localhost:3000/aditor/upload"
          enctype="multipart/form-data"
          method="post"
          ref="upload"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :on-success="uploadSuccess"
          :file-list="fileList"
          class="iconbig"
          :headers="headers"
        >
          <i class="el-icon-camera-solid"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="" />
        </el-dialog>
      </el-form-item>
      <br />
      <!-- 
        :action是执行上传动作的后台接口，el-button是触发上传的按钮 
        -->
      <!-- 富文本编辑器 -->
      <el-form-item label="正文" prop="content">
        <div style="border: 1px solid #ccc">
          <Toolbar
            style="border-bottom: 1px solid #ccc"
            :editor="editor"
            :defaultConfig="toolbarConfig"
            :mode="mode"
          />
          <Editor
            style="height: 500px; overflow-y: hidden"
            ref="wangEditor"
            :defaultConfig="editorConfig"
            v-model="formData.content"
            :mode="mode"
            @onCreated="onCreated"
          />
        </div>
      </el-form-item>

      <!-- 按钮 -->
      <el-form-item>
        <el-button type="primary" @click="handlePublish">发布</el-button>
        <el-button type="warning" @click="handleCancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import Vue from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'

export default Vue.extend({
  components: { Editor, Toolbar },
  data() {
    return {
      editor: null, //实例
      toolbarConfig: {}, //工具栏配置
      editorConfig: {
        placeholder: '请输入内容...',
        // 所有的菜单配置，都要在 MENU_CONF 属性下
        MENU_CONF: {
          // 配置上传图片
          uploadImage: {
            // token: localStorage.getItem('token'),
            // http://localhost:3000/aditor/upload
            // 'Access-Control-Allow-Origin': 'origin',
            // 后端上传地址，必填
            server: 'http://localhost:3000/aditor/uploads',
            // form-data fieldName，后端接口参数名称，默认值wangeditor-uploaded-image
            fieldName: 'file',
            // 1M，单个文件的最大体积限制，默认为 2M
            maxFileSize: 1 * 1024 * 1024,
            // 最多可上传几个文件，默认为 100
            maxNumberOfFiles: 10,
            // 选择文件时的类型限制，默认为 ['image/*'] 。如不想限制，则设置为 []
            allowedFileTypes: ['image/*'],
            // 15 秒，超时时间，默认为 10 秒
            timeout: 15 * 1000,
          },
        },
      },

      mode: 'default', // or 'simple'
      categories: [],
      formData: {
        title: '',
        author: '',
        category: '',
        abstract: '',
        imageUrl: '',
        content: '',
      },
      fileList: [],
      // 图片校验
      // form: {
      //   file: '',
      // },
      // 图片上传组件
      dialogImageUrl: '',
      dialogVisible: false,
      // 输入规则
      Rules: {
        title: [{ required: true, message: '标题不能为空', trigger: 'blur' }],
        author: [{ required: true, message: '作者不能为空', trigger: 'blur' }],
        category: [
          { required: true, message: '分类不能为空', trigger: 'blur' },
        ],
        abstract: [
          { required: true, message: '概要不能为空', trigger: 'blur' },
        ],
      },
    }
  },
  computed: {
    //给headers直接获取一个token,通过后后面的全局token验证
    headers() {
      return { Authorization: 'Bearer ' + localStorage.getItem('token') }
    },
  },
  // 生命周期
  created() {
    this.getCategory()
    const id = this.$route.query.ID
    // 先判断是否是编辑
    if (id) {
      this.$http.get(`/articles/${id}`).then((data) => {
        this.formData.title = data.result.title
        this.formData.author = data.result.author
        this.formData.category = data.result.category_id
        this.formData.abstract = data.result.abstract
        this.formData.imageUrl = data.result.image_address
        this.formData.content = data.result.content
        //console.log(this.formData.imageUrl)
        this.fileList.push({ url: this.formData.imageUrl })
      })
    }
  },
  // 富文本编辑器
  mounted() {
    // 模拟 ajax 请求，异步渲染编辑器
    setTimeout(() => {
      this.html = ''
    }, 1500)
  },
  beforeDestroy() {
    const editor = this.editor
    if (editor == null) return
    editor.destroy() // 组件销毁时，及时销毁编辑器
  },
  methods: {
    // 富文本编辑器
    onCreated(editor) {
      this.editor = Object.seal(editor) // 一定要用 Object.seal() ，否则会报错
    },

    // 获取数据库分类数据
    getCategory() {
      this.$http.get(`/categories/?page=1&size=100`).then((data) => {
        this.categories = data.result.data
        // console.log(this.categories)
      })
    },
    // 图片上传
    // 上传图片成功的响应
    uploadSuccess(response, file, filelist) {
      // console.log(response)
      this.formData.imageUrl = response.url
    },
    //图片移除
    handleRemove(file, fileList) {
      let url = ''
      const id = this.$route.query.ID
      if (id) {
        url = file.url
      } else {
        url = file.response.url
      }
      this.$http.post(`/aditor/delete`, { url }).then((data) => {
        const { message } = data
        console.log(message)
      })
    },
    // 图片点击
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    // // 图片改变
    // onChange(file, fileList) {
    //   this.form.file = fileList
    //   console.log(this.form.file)
    // },

    // 遍历清空对象
    clearValue(obj) {
      Object.keys(obj).forEach((key) => {
        if (typeof obj[key] == 'object') {
          this.clearValue(obj[key])
        } else {
          obj[key] = ''
        }
      })
    },

    // 监听发布
    handlePublish() {
      const id = this.$route.query.ID
      // console.log(id)
      this.$refs['form'].validate((valid) => {
        if (valid) {
          // 判断是否修改,发送put
          if (id) {
            this.$http.put(`/articles/${id}`, this.formData).then((data) => {
              const { code, message } = data
              if (code != 0) {
                this.$message.error(message)
                return
              }
              this.$message({
                type: 'success',
                message: message,
                showClose: true,
                duration: 1000,
              })
              // 清空表单
              this.clearValue(this.formData)
              // 清除图片
              this.$refs.upload.clearFiles()
              // 清空编辑器内容
              this.editor.clear()
              //返回文章管理
              this.$router.push('/article')
            })
          } else {
            // 发送post
            this.$http.post(`/articles`, this.formData).then((data) => {
              const { code, message } = data
              if (code != 0) {
                // 提示,抛出异常
                this.$message.error(message)
                return
              }
              this.$message({
                type: 'success',
                message: message,
                showClose: true,
                duration: 1000,
              })
              // 清空表单
              this.clearValue(this.formData)
              // 清除图片
              this.$refs.upload.clearFiles()
              // 清空编辑器内容
              this.editor.clear()
              //返回文章管理
              this.$router.push('/article')
            })
          }
        }
      })
    },

    // 取消发布
    handleCancel() {
      this.$router.push('/article')
    },
  },
})
</script>

<style src="@wangeditor/editor/dist/css/style.css"></style>
<style scoped>
.inputtext {
  width: 900px;
}
</style>
